/**
 * 语音管理器 - 内存优化版本
 */

import { memoryManager } from './performance.js';

export class VoiceManager {
  constructor(options = {}) {
    this.options = {
      maxCacheSize: 20,           // 最大缓存语音数量
      maxAudioSize: 10 * 1024 * 1024, // 最大音频大小（10MB）
      enableCompression: true,     // 启用压缩
      enableStreaming: true,       // 启用流式播放
      preloadCount: 3,            // 预加载数量
      ...options
    };
    
    this.audioCache = new Map();
    this.loadingAudios = new Set();
    this.failedAudios = new Set();
    this.currentAudio = null;
    this.playQueue = [];
    this.isPlaying = false;
    
    this.initAudioContext();
  }
  
  // 初始化音频上下文
  initAudioContext() {
    try {
      this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
    } catch (error) {
      console.warn('AudioContext not supported:', error);
    }
  }
  
  // 加载语音
  async loadVoice(url, options = {}) {
    // 检查缓存
    const cachedAudio = this.getCachedAudio(url);
    if (cachedAudio) {
      return cachedAudio;
    }
    
    // 检查是否正在加载
    if (this.loadingAudios.has(url)) {
      return new Promise((resolve, reject) => {
        const checkLoading = () => {
          if (this.audioCache.has(url)) {
            resolve(this.audioCache.get(url));
          } else if (this.failedAudios.has(url)) {
            reject(new Error('Audio load failed'));
          } else {
            setTimeout(checkLoading, 100);
          }
        };
        checkLoading();
      });
    }
    
    // 检查是否加载失败
    if (this.failedAudios.has(url)) {
      throw new Error('Audio load failed');
    }
    
    try {
      this.loadingAudios.add(url);
      
      // 创建音频对象
      const audio = new Audio();
      audio.crossOrigin = 'anonymous';
      audio.preload = 'auto';
      
      // 设置音频属性
      if (options.volume !== undefined) {
        audio.volume = options.volume;
      }
      
      // 加载音频
      await this.loadAudio(audio, url);
      
      // 缓存音频
      this.cacheAudio(url, audio);
      
      return audio;
      
    } catch (error) {
      console.error('Voice load error:', error);
      this.failedAudios.add(url);
      throw error;
    } finally {
      this.loadingAudios.delete(url);
    }
  }
  
  // 加载音频
  loadAudio(audio, url) {
    return new Promise((resolve, reject) => {
      audio.oncanplaythrough = () => {
        resolve(audio);
      };
      
      audio.onerror = () => {
        reject(new Error('Audio load failed'));
      };
      
      audio.onloadstart = () => {
        // 检查音频大小
        if (this.estimateAudioSize(audio) > this.options.maxAudioSize) {
          reject(new Error('Audio too large'));
        }
      };
      
      audio.src = url;
      audio.load();
    });
  }
  
  // 播放语音
  async playVoice(url, options = {}) {
    try {
      // 停止当前播放
      if (this.isPlaying) {
        this.stopCurrentVoice();
      }
      
      // 加载音频
      const audio = await this.loadVoice(url, options);
      
      // 设置播放选项
      if (options.volume !== undefined) {
        audio.volume = options.volume;
      }
      
      if (options.loop !== undefined) {
        audio.loop = options.loop;
      }
      
      // 播放音频
      await this.playAudio(audio);
      
      this.currentAudio = audio;
      this.isPlaying = true;
      
      return audio;
      
    } catch (error) {
      console.error('Voice play error:', error);
      throw error;
    }
  }
  
  // 播放音频
  playAudio(audio) {
    return new Promise((resolve, reject) => {
      audio.onended = () => {
        this.isPlaying = false;
        this.currentAudio = null;
        resolve();
      };
      
      audio.onerror = () => {
        this.isPlaying = false;
        this.currentAudio = null;
        reject(new Error('Audio play failed'));
      };
      
      audio.play().then(resolve).catch(reject);
    });
  }
  
  // 暂停语音
  pauseVoice() {
    if (this.currentAudio && !this.currentAudio.paused) {
      this.currentAudio.pause();
    }
  }
  
  // 恢复语音
  resumeVoice() {
    if (this.currentAudio && this.currentAudio.paused) {
      this.currentAudio.play();
    }
  }
  
  // 停止语音
  stopVoice() {
    if (this.currentAudio) {
      this.currentAudio.pause();
      this.currentAudio.currentTime = 0;
      this.isPlaying = false;
      this.currentAudio = null;
    }
  }
  
  // 停止当前语音
  stopCurrentVoice() {
    this.stopVoice();
  }
  
  // 设置音量
  setVolume(volume) {
    if (this.currentAudio) {
      this.currentAudio.volume = Math.max(0, Math.min(1, volume));
    }
  }
  
  // 获取当前音量
  getVolume() {
    return this.currentAudio ? this.currentAudio.volume : 1;
  }
  
  // 获取缓存的音频
  getCachedAudio(url) {
    const cached = this.audioCache.get(url);
    if (cached) {
      cached.lastAccess = Date.now();
      return cached.audio;
    }
    return null;
  }
  
  // 缓存音频
  cacheAudio(url, audio) {
    // 检查缓存大小
    if (this.audioCache.size >= this.options.maxCacheSize) {
      this.evictOldestAudio();
    }
    
    this.audioCache.set(url, {
      audio,
      timestamp: Date.now(),
      lastAccess: Date.now(),
      size: this.estimateAudioSize(audio)
    });
  }
  
  // 估算音频大小
  estimateAudioSize(audio) {
    // 这是一个估算值，实际大小可能不同
    return audio.duration * 16000; // 假设16kbps
  }
  
  // 驱逐最旧的音频
  evictOldestAudio() {
    let oldestKey = null;
    let oldestTime = Date.now();
    
    for (const [key, item] of this.audioCache.entries()) {
      if (item.lastAccess < oldestTime) {
        oldestTime = item.lastAccess;
        oldestKey = key;
      }
    }
    
    if (oldestKey) {
      const item = this.audioCache.get(oldestKey);
      if (item.audio !== this.currentAudio) {
        this.audioCache.delete(oldestKey);
      }
    }
  }
  
  // 预加载语音
  async preloadVoices(urls) {
    const promises = urls.slice(0, this.options.preloadCount).map(url => 
      this.loadVoice(url).catch(error => {
        console.warn('Preload failed:', url, error);
        return null;
      })
    );
    
    return Promise.allSettled(promises);
  }
  
  // 清理缓存
  clearCache() {
    // 停止当前播放
    this.stopVoice();
    
    // 清理缓存
    this.audioCache.clear();
    this.loadingAudios.clear();
    this.failedAudios.clear();
  }
  
  // 获取缓存统计
  getCacheStats() {
    let totalSize = 0;
    for (const item of this.audioCache.values()) {
      totalSize += item.size;
    }
    
    return {
      cacheSize: this.audioCache.size,
      totalSize: Math.round(totalSize / 1024), // KB
      loadingCount: this.loadingAudios.size,
      failedCount: this.failedAudios.size,
      isPlaying: this.isPlaying
    };
  }
  
  // 获取当前播放状态
  getPlayState() {
    if (!this.currentAudio) {
      return { isPlaying: false, currentTime: 0, duration: 0 };
    }
    
    return {
      isPlaying: !this.currentAudio.paused,
      currentTime: this.currentAudio.currentTime,
      duration: this.currentAudio.duration,
      volume: this.currentAudio.volume
    };
  }
  
  // 销毁管理器
  destroy() {
    this.stopVoice();
    this.clearCache();
    
    if (this.audioContext) {
      this.audioContext.close();
    }
  }
}

// 语音播放组件混入
export const voiceMixin = {
  data() {
    return {
      voiceManager: null,
      currentVoiceUrl: null,
      isVoicePlaying: false,
      voiceVolume: 1
    };
  },
  
  created() {
    this.voiceManager = new VoiceManager();
  },
  
  beforeDestroy() {
    if (this.voiceManager) {
      this.voiceManager.destroy();
    }
  },
  
  methods: {
    async playVoice(url, options = {}) {
      try {
        this.currentVoiceUrl = url;
        this.isVoicePlaying = true;
        
        await this.voiceManager.playVoice(url, {
          volume: this.voiceVolume,
          ...options
        });
        
        this.$emit('voice-play', { url, options });
        
      } catch (error) {
        this.isVoicePlaying = false;
        this.$emit('voice-error', { url, error });
        throw error;
      }
    },
    
    pauseVoice() {
      this.voiceManager.pauseVoice();
      this.$emit('voice-pause', { url: this.currentVoiceUrl });
    },
    
    resumeVoice() {
      this.voiceManager.resumeVoice();
      this.$emit('voice-resume', { url: this.currentVoiceUrl });
    },
    
    stopVoice() {
      this.voiceManager.stopVoice();
      this.isVoicePlaying = false;
      this.$emit('voice-stop', { url: this.currentVoiceUrl });
    },
    
    setVoiceVolume(volume) {
      this.voiceVolume = volume;
      this.voiceManager.setVolume(volume);
    }
  }
};

// 导出单例实例
export const voiceManager = new VoiceManager();

// 全局注册
if (typeof window !== 'undefined') {
  window.voiceManager = voiceManager;
}
